import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_danli.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/config/prefs.dart';
import 'package:love_app/enum/sex.dart';
import 'package:love_app/model/home_page_model.dart' as HPModel;
import 'package:love_app/pages/home_page/first_ui/center_box.dart';
import 'package:love_app/providers/bg_model.dart';
import 'package:love_app/providers/home_page_provider.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:love_app/pages/home_page/first_ui/alert_dialog.dart';
import 'package:love_app/pages/home_page/first_ui/my_bottom_sheet.dart';
import 'package:love_app/pages/home_page/first_ui/top_box_clipper.dart';
import 'package:love_app/routes/application.dart';
import 'package:love_app/routes/routes.dart';
import 'package:love_app/service/home_page_api.dart';
import 'package:provider/provider.dart';

// homePage第一页内容
class FirstTopBox extends StatefulWidget {
  @override
  _FirstTopBoxState createState() => _FirstTopBoxState();
}

class _FirstTopBoxState extends State<FirstTopBox> {
  ShareProvider _shareProvider;
  BgModel _bgModel;
  HPModel.Data _homePageModel;

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
    _bgModel = Provider.of<BgModel>(context, listen: false);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _bgImage(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return _body();
        }
        return SuDialog.futureBuildLoding(textColor: _shareProvider.textColor);
        // return Container();
      },
    );
  }

  // 页面内容
  Widget _body() {
    return FutureBuilder(
      future: _getHomePageData(_shareProvider.token),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          _homePageModel = snapshot.data.data;
          return _futureBuildChild();
        }
        // return SuDialog.futureBuildLoding(textColor: _shareProvider.textColor);
        return Container();
      },
    );
  }

  // 异步widget_child
  Widget _futureBuildChild() {
    return Column(
      children: <Widget>[
        ClipPath(
          clipper: TopBoxClipper(),
          child: _topBox(),
        ),
        Stack(
          overflow: Overflow.visible,
          children: <Widget>[
            CenterBox(
              homePageModel: _homePageModel,
            ),
            _homePageModel.bindLover == 1 ? _loveHeaderImg() : Container(),
          ],
        ),
      ],
    );
  }

  // 异步widget获取数据
  Future _getHomePageData(String token) async {
    return Application.memoizer.runOnce(() async {
      HPModel.HomePageModel homePageModel = await HomePageApi().userInfo(token);
      return homePageModel;
    });
  }

  // 规则的矩形
  Widget _topBox() {
    return InkWell(
      onTap: () {
        _switchBackgound();
      },
      child: Container(
        child: Consumer<BgModel>(
          builder: (context, BgModel bgModel, child) => Container(
            height: ScreenUtil().setHeight(708),
            width: ScreenUtil().setWidth(750),
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: bgModel.firstBgImage, fit: BoxFit.cover),
            ),
            child: _allPositionedWidget(),
          ),
        ),
      ),
    );
  }

  // 点击背景图片弹窗
  Future _switchBackgound() {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return BackgtoundOpenDialog();
      },
    );
  }

  // 所有的定位控件
  Widget _allPositionedWidget() {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        _title(), // 标题
        _lefMessale(), // 左上角小邮件
        _mapMarkerAlt(), // 右边定位
        _hasBindLover(), // 是否绑定另一半
        _arrowButton(), // 右边透明盒子， 箭头，点击显示更多
      ],
    );
  }

  // 是否绑定了另一把
  Widget _hasBindLover() {
    if (_homePageModel.bindLover == 0) {
      return _bindLover(); // 左边透明盒子，绑定另一半
    }
    return _loveDay(); // 绑定天数
  }

  // 标题栏
  Positioned _title() {
    return Positioned(
      top: Su().h(69.0),
      child: Text(
        '恋爱记',
        style: Su().textStyle(Colors.white, 36.0),
      ),
    );
  }

  // 左边的小邮箱
  Positioned _lefMessale() {
    return Positioned(
      top: ScreenUtil().setHeight(69.0),
      left: ScreenUtil().setWidth(27.0),
      child: Icon(
        FontAwesomeIcons.envelope,
        color: Colors.white,
      ),
    );
  }

  // 左边的透明盒子
  Widget _bindLover() {
    return Positioned(
      bottom: ScreenUtil().setHeight(51),
      left: ScreenUtil().setWidth(0),
      child: Container(
        width: ScreenUtil().setWidth(409.0),
        height: ScreenUtil().setHeight(128.0),
        decoration: BoxDecoration(
          color: Color.fromRGBO(255, 255, 255, 0.2),
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(56),
            bottomRight: Radius.circular(56),
          ),
        ),
        child: _bindLoverChild(),
      ),
    );
  }

  // 左边透明盒子、文字说明
  Widget _bindLoverChild() {
    return Row(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(left: ScreenUtil().setWidth(51)),
          width: ScreenUtil().setWidth(194),
          child: Text(
            '体验全部情侣功能 请先绑定另一半',
            style: Su().textStyle(Color.fromRGBO(82, 82, 82, 1), 24),
          ),
        ),
        // 绑定另一半
        Container(
            width: ScreenUtil().setWidth(110),
            height: ScreenUtil().setWidth(110),
            margin: EdgeInsets.only(
              left: ScreenUtil().setWidth(30),
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(ScreenUtil().setWidth(90)),
              color: _shareProvider.textColor,
            ),
            child: _other(context)),
      ],
    );
  }

  // 相恋天数定位（当有绑定伴侣显示）
  Positioned _loveDay() {
    return Positioned(
      left: Su().w(51),
      top: Su().h(402),
      child: _loveDayChild(),
    );
  }

  // 相恋天数（当有绑定伴侣显示）
  Widget _loveDayChild() {
    return Container(
      alignment: Alignment.center,
      width: Su().w(245),
      height: Su().h(180),
      child: Column(
        children: <Widget>[
          Text(
            "相恋${_homePageModel.loveLogSum}天",
            style: Su().textStyle(Colors.white, 45),
          ),
          Text(
            "双方连续登陆${_homePageModel.meetingDaySum}天",
            style: Su().textStyle(Colors.white, 32),
          ),
        ],
      ),
    );
  }

  // 定位头像（当有绑定伴侣显示）
  Positioned _loveHeaderImg() {
    return Positioned(
      left: Su().w(50),
      bottom: Su().h(450),
      child: Container(
        height: Su().h(104),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _loveHeaderImgFirst(),
            _loveHeaderImgSecond(),
          ],
        ),
      ),
    );
  }

  // 第一个头像
  Widget _loveHeaderImgFirst() {
    return InkWell(
      onTap: (){
        Su.suPrints("哈哈哈");
      },
      child: ClipOval(
        child: Image.network(
          _homePageModel.myInfo.headimg,
          width: Su().w(104),
          height: Su().w(104),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 第二个头像
  Widget _loveHeaderImgSecond() {
    return Padding(
      padding: EdgeInsets.only(left: Su().w(10)),
      child: InkWell(
        onTap: () {
          var loveUserId = _shareProvider.loverInfo.uid;
          Application.router
              .navigateTo(context, Routes.userCenter + "?userId=$loveUserId");
        },
        child: ClipOval(
          child: Image.network(
            _homePageModel.loverInfo.headimg,
            width: Su().w(104),
            height: Su().w(104),
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }

  // 邀请另一半按钮
  Widget _other(BuildContext context) {
    return InkWell(
      onTap: () async {
        await _showModealBottomSheet();
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '邀请',
            style: Su().textStyle(Colors.white, 24),
          ),
          Text(
            '另一半',
            style: Su().textStyle(Colors.white, 24),
          ),
        ],
      ),
    );
  }

  Future _showModealBottomSheet() {
    return showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return MyBottomSheet();
      },
    );
  }

  // 地址定位图标
  Positioned _mapMarkerAlt() {
    return Positioned(
      bottom: ScreenUtil().setHeight(211.0),
      right: ScreenUtil().setHeight(10),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(right: 4.0),
            child: Icon(
              FontAwesomeIcons.mapMarkerAlt,
              color: Colors.white,
              size: 15,
            ),
          ),
          Text(
            _homePageModel.loginAddress,
            style: Su().textStyle(Colors.white, 26.0),
          )
        ],
      ),
    );
  }

  // 点击箭头显示更多
  Widget _arrowButton() {
    return Positioned(
      bottom: Su().h(79),
      right: Su().w(0),
      child: Consumer<HomePageProvider>(
        builder: (context, HomePageProvider homePageModel, child) => InkWell(
          onTap: () {
            homePageModel.updateModel();
          },
          child: Container(
            width: Su().w(141.0),
            height: Su().h(79.0),
            decoration: BoxDecoration(
              color: Color.fromRGBO(255, 255, 255, 0.3),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(56),
                bottomLeft: Radius.circular(56),
              ),
            ),
            child: _arrowIcondOther(),
          ),
        ),
      ),
    );
  }

  // (position)箭头图标， 点击显示更多的样式
  Widget _arrowIcondOther() {
    return Row(
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(
            left: ScreenUtil().setWidth(20),
          ),
          child: Icon(
            IconData(0xe612, fontFamily: 'loveIcon'),
            color: _shareProvider.textColor,
            size: Su().w(40),
          ),
        ),
        Container(
          padding: EdgeInsets.only(
            left: ScreenUtil().setWidth(10),
            // right: ScreenUtil().setWidth(10)
          ),
          child: Text(
            '更多',
            style: Su().textStyle(Colors.white, 28),
          ),
        ),
      ],
    );
  }

  // 异步获取背景图片
  Future<void> _bgImage() async {
    // String key = Prefs.firstPage + _shareProvider.uid.toString();
    // var pres = await Su().presObject();
    // String fileName = pres.get(key);
    // if (fileName == null) {
    //   if (_shareProvider.sex == Sex.boy) {
    //     _bgModel.firstBgImage = AssetImage("images/home_page_img/first_page_boy.png");
    //   }
    //   _bgModel.firstBgImage = AssetImage("images/home_page_img/first_page_girl.png");
    // }else{
    //   _bgModel.firstBgImage = FileImage(File(fileName));
    // }

    return SuDanli.memoizer.runOnce(() async {
      String key = Prefs.firstPage + _shareProvider.uid.toString();
      var pres = await Su().presObject();
      String fileName = pres.get(key);
      if (fileName == null) {
        if (_shareProvider.sex == Sex.boy) {
          _bgModel.firstBgImage =
              AssetImage("images/home_page_img/first_page_boy.png");
        }
        _bgModel.firstBgImage =
            AssetImage("images/home_page_img/first_page_girl.png");
      } else {
        _bgModel.firstBgImage = FileImage(File(fileName));
      }
    });
  }
}
